﻿<template>
  <div class="app-container">
    <div class="filter-title">
      <el-form label-position="right" label-width="95px">
        <el-form-item :label="$t('broadcast.name')+' :'">
          <el-input
            v-model="listQuery.name"
            style="width: 150px"
            class="filter-item"
            :placeholder="$t('broadcast.name')"
            @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('public.status')+' :'">
          <el-select
            v-model="listQuery.status"
            clearable
            style="width: 150px"
            class="filter-item"
            :placeholder="$t('public.status')"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('broadcast.playStatus')+' :'">
          <el-select
            v-model="listQuery.play_status"
            clearable
            style="width: 150px"
            class="filter-item"
            :placeholder="$t('broadcast.playStatus')"
          >
            <el-option
              v-for="item in playOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-button
          style="margin-left:20px"
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleFilter"
        >{{ $t('table.search') }}</el-button>
        <el-button
          v-if="permission.add"
          style="margin-left: 10px;float:right"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >{{ $t('table.add') }}</el-button>
        <el-button
          style="margin-left: 10px"
          class="filter-item"
          type="primary"
          @click="handleRefresh"
        >{{ $t('table.refresh') }}</el-button>
        <div v-show="!showSearchItem" class="showDown" @click="showSearchItem = true">
          <i class="el-icon-d-arrow-right"></i>
        </div>
        <div v-show="showSearchItem" class="showUp" @click="showSearchItem = false">
          <i class="el-icon-d-arrow-left"></i>
        </div>
      </el-form>
    </div>
    <div v-show="showSearchItem" class="filter-container">
      <el-form label-position="right" label-width="95px">
        <el-form-item v-if="type === 1" :label="$t('broadcast.region')+' :'">
          <el-input
            v-model="listQuery.regions_name"
            style="width: 150px"
            class="filter-item"
            :placeholder="$t('broadcast.region')"
            @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="type === 1" :label="$t('broadcast.trade')+' :'">
          <el-input
            v-model="listQuery.trade_name"
            style="width: 150px"
            class="filter-item"
            :placeholder="$t('broadcast.trade')"
            @keyup.enter.native="handleFilter"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('broadcast.data')+' :'">
          <div class="filter-item">
            <el-date-picker
              v-model="listQuery.startTime"
              :picker-options="pickerOptionsB"
              type="date"
              :placeholder="$t('broadcast.startTime')"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </div>
          <div class="filter-item">
            <el-date-picker
              v-model="listQuery.endTime"
              :picker-options="pickerOptionsE"
              type="date"
              :placeholder="$t('broadcast.endTime')"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255,255,255,0.2)"
      border
      fit
      highlight-current-row
      style="width: 100%min-height:1000px"
    >
      <el-table-column fixed="left" align="center" :label="$t('table.id')" width="65">
        <template slot-scope="scope">
          <span>{{ (listQuery.page-1)*listQuery.limit+scope.$index+1 }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('broadcast.name')">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('broadcast.content')">
        <template slot-scope="scope">
          <span>{{ scope.row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('broadcast.startTime')">
        <template slot-scope="scope">
          <span>{{ timeFormat(scope.row.start_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('broadcast.endTime')">
        <template slot-scope="scope">
          <span>{{ timeFormat(scope.row.end_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('broadcast.region')">
        <template slot-scope="scope">
          <span>{{ scope.row.regions_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip :label="$t('broadcast.trade')">
        <template slot-scope="scope">
          <span>{{ scope.row.trade_name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('broadcast.playStatus')">
        <template slot-scope="scope">
          <span>{{ playEs(scope.row.play_status) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('public.status')">
        <template slot-scope="scope">
          <span
            :class="statusColorSecond(scope.row.status)"
          >{{ statusEstimation(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        :label="$t('table.actions')"
        :width="operWidth"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            @click="handleRead(scope.row)"
          >{{ $t('table.read') }}</el-button>
          <el-button
            v-if="permission.update"
            type="primary"
            size="mini"
            :disabled="(scope.row.status !== 2 && scope.row.status !== 4)?false:true"
            @click="handleUpdate(scope.row)"
          >{{ $t('table.edit') }}</el-button>
          <el-button
            v-if="scope.row.status === 2 && permission.review"
            type="danger"
            size="mini"
            @click="handleDisable(scope.row)"
          >{{ $t('table.disable') }}</el-button>
          <el-button
            v-else-if="scope.row.status === 4 && permission.review"
            type="success"
            size="mini"
            @click="handleEnable(scope.row)"
          >{{ $t('table.enable') }}</el-button>
          <el-button
            v-if="permission.review && scope.row.status !== 2 && scope.row.status !== 4"
            type="primary"
            size="mini"
            @click="handleReview(scope.row)"
          >{{ $t('table.review') }}</el-button>
          <el-button
            v-if="permission.del"
            size="mini"
            type="danger"
            :disabled="(scope.row.status !== 2 && scope.row.status !== 4)?false:true"
            @click="handleModifyStatus(scope.row,'deleted')"
          >{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!-- 编辑 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="35%"
        style="width: 400px margin-left:120px"
        size="small"
      >
        <el-form-item v-if="dialogStatus!='review'" :label="$t('broadcast.name')+' :'" prop="name">
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item v-else :label="$t('broadcast.name')+' :'">
          <span>{{ temp.name }}</span>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus!='review'"
          class="filter-rule"
          :label="$t('broadcast.data')+' :'"
          prop="data"
        >
          <div class="filter-item">
            <el-date-picker
              v-model="temp.start_time"
              :picker-options="pickerOptionsBT"
              type="date"
              placeholder="开始日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </div>
          <div class="filter-item">
            <el-date-picker
              v-model="temp.end_time"
              :picker-options="pickerOptionsET"
              type="date"
              placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item v-else :label="$t('broadcast.data')+' :'">
          <span>{{ getData(temp.start_time) }}&nbsp;至&nbsp;{{ getData(temp.end_time) }}</span>
        </el-form-item>
        <el-form-item v-if="type !== 3" :label="$t('public.region')+' :'">
          <select-page
            v-if="dialogStatus!=='review'"
            :id="temp.regions_id"
            :name="temp.regions_name"
            style="width:200px"
            placeholder="请选择区域"
            key-field="id"
            show-field="name"
            :data="areaOptions"
            :count="areaCount"
            :page-size="pageSize"
            @getList="getAreaList"
            @values="getAreaid"
          ></select-page>
          <span v-else-if="temp.region_name">{{ temp.region_name }}</span>
        </el-form-item>
        <el-form-item v-if="type !==3" :label="$t('public.trade')+' :'">
          <select-page
            v-if="dialogStatus!=='review'"
            :id="temp.trade_id"
            :name="temp.trade_name"
            style="width:200px"
            placeholder="请选择行业"
            key-field="id"
            show-field="name"
            :data="industryOptions"
            :count="industryCount"
            :page-size="pageSize"
            @getList="getIndustryList"
            @values="getIndustryid"
          ></select-page>
          <span v-else-if="temp.trade_name">{{ temp.trade_name }}</span>
        </el-form-item>
        <el-form-item :label="$t('rule.equipmentCode')+' :'" :prop="type ===3 ? 'equipment_id': ''">
          <select-page
            v-if="dialogStatus!=='review'"
            :id="temp.equipment_id"
            :name="temp.equipment_code"
            style="width:200px"
            placeholder="请选择广告机"
            key-field="id"
            show-field="name"
            :data="equipmentOptions"
            :count="equipmentCount"
            :page-size="pageSize"
            @getList="getEquipmentList"
            @values="getEquipmentid"
          ></select-page>
          <span v-else-if="temp.equipment_code">{{ temp.equipment_code }}</span>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus==='review' && temp.content"
          :label="$t('broadcast.content')+' :'"
        >
          <span>{{ temp.content }}</span>
        </el-form-item>
        <el-form-item
          v-else-if="dialogStatus!=='review'"
          :label="$t('broadcast.content')+' :'"
          prop="content"
        >
          <el-input v-model="temp.content" type="textarea"></el-input>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus!='review'"
          :label="$t('broadcast.count')+' :'"
          prop="count"
        >
          <el-input-number v-model="temp.count" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item v-else :label="$t('broadcast.count')+' :'">
          <span>{{ temp.count }}</span>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus=='review'"
          :label="$t('public.checkStatus')+' :'"
          prop="status"
        >
          <el-radio-group v-model="temp.status">
            <el-radio :label="1" disabled>审核中</el-radio>
            <el-radio :label="2">审核通过</el-radio>
            <el-radio :label="3">未通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="dialogStatus!=='create' && temp.status === 3"
          :label="$t('public.auditOpinion')+' :'"
          prop="check_remark"
        >
          <el-input
            v-if="dialogStatus!=='create' && permission.review"
            v-model="temp.check_remark"
            type="textarea"
          ></el-input>
          <span v-if="dialogStatus==='update' && !(permission.review)">{{ temp.check_remark }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button
          v-if="dialogStatus=='create'"
          type="primary"
          :disabled="!createDisabled"
          @click="createData"
        >{{ $t('table.confirm') }}</el-button>
        <el-button
          v-else-if="dialogStatus=='review'"
          type="primary"
          :disabled="!createDisabled"
          @click="reviewData"
        >{{ $t('table.confirm') }}</el-button>
        <el-button
          v-else
          type="primary"
          :disabled="!updateDisabled"
          @click="updateData"
        >{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormRead">
      <el-form
        :model="temp"
        label-position="right"
        label-width="40%"
        style="width: 400px margin-left:120px"
      >
        <el-form-item :label="$t('broadcast.name')+' :'">
          <span>{{ temp.name }}</span>
        </el-form-item>
        <el-form-item :label="$t('broadcast.data')+' :'">
          <span>{{ getData(temp.start_time) }}&nbsp;至&nbsp;{{ getData(temp.end_time) }}</span>
        </el-form-item>
        <el-form-item v-if="temp.regions_name" :label="$t('public.region')+' :'">
          <span>{{ temp.regions_name }}</span>
        </el-form-item>
        <el-form-item v-if="temp.trade_name" :label="$t('public.trade')+' :'">
          <span>{{ temp.trade_name }}</span>
        </el-form-item>
        <el-form-item v-if="temp.equipment_code" :label="$t('rule.equipmentCode')+' :'">
          <span>{{ temp.equipment_code }}</span>
        </el-form-item>
        <el-form-item :label="$t('broadcast.content')+' :'">
          <span>{{ temp.content }}</span>
        </el-form-item>
        <el-form-item :label="$t('broadcast.count')+' :'">
          <span>{{ temp.count }}</span>
        </el-form-item>
        <el-form-item v-if="temp.status === 3" :label="$t('public.auditOpinion')+' :'">
          <span>{{ temp.check_remark }}</span>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import selectPage from "@/views/select/SelectPage"; // 分页选择控件
import { getToken } from "@/utils/auth"; // get token from cookie

export default {
  name: "Broadcast",
  components: {
    "select-page": selectPage
  },
  data() {
    const name = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("规则名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error(
                "规则名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号"
              )
            );
          }
        }
      } else {
        callback(new Error("请填写规则名称"));
      }
    };
    const remark = (rule, value, callback) => {
      if (value) {
        if (value.length <= 0) {
          callback(new Error("请输入审核意见"));
        } else if (value.length > 300) {
          callback(new Error("审核意见不能超过300个字符"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入审核意见"));
      }
    };
    const content = (rule, value, callback) => {
      if (value) {
        if (value.length >= 20 && value.length <= 200) {
          callback();
        } else {
          callback(new Error("规则描述不能低于20个字符且不超过200个字符"));
        }
      } else {
        callback(new Error("请输入广播内容"));
      }
    };
    const getData = (rule, value, callback) => {
      if (this.temp.start_time && this.temp.end_time) {
        callback();
      } else {
        callback(new Error("请选择规则日期"));
      }
    };
    const count = (rule, value, callback) => {
      if (value) {
        if (value >= 0 && value <= 100) {
          callback();
        } else {
          callback(new Error("播放次数应大于0且小于100"));
        }
      } else {
        callback(new Error("请填写播放次数"));
      }
    };

    return {
      showSearchItem: false,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      type: "",
      statusOptions: [
        {
          value: 1,
          label: "审核中"
        },
        {
          value: 2,
          label: "审核通过"
        },
        {
          value: 3,
          label: "未通过"
        },
        {
          value: 4,
          label: "禁用"
        }
      ],
      playOptions: [
        {
          value: 1,
          label: "待播放"
        },
        {
          value: 2,
          label: "播放中"
        },
        {
          value: 3,
          label: "已结束"
        }
      ],
      listQuery: {
        page: 1,
        limit: 20,
        name: "",
        status: "",
        play_status: "",
        regions_name: "",
        trade_name: "",
        startTime: "",
        endTime: ""
      },
      temp: {
        id: undefined,
        name: "",
        content: "",
        trade_id: "",
        trade_name: "",
        regions_id: "",
        regions_name: "",
        equipment_id: "",
        equipment_code: "",
        count: "",
        play_time: "",
        start_time: "",
        end_time: ""
      },
      temptime: [{ start: "", end: "" }],
      dialogFormVisible: false,
      dialogFormRead: false,
      dialogStatus: "",
      upLoading: false,
      visibleVideo: false,
      textMap: {
        update: "更新",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        name: [{ required: true, trigger: "blur", validator: name }],
        ad_id: [{ required: true, message: "请选择广告主", trigger: "change" }],
        video_id: [
          { required: true, message: "请选择视频源", trigger: "change" }
        ],
        data: [{ required: true, trigger: "blur", validator: getData }],
        content: [{ required: true, trigger: "blur", validator: content }],
        count: [{ required: true, trigger: "blur", validator: count }],
        status: [{ required: true, message: "请审核", trigger: "change" }],
        check_remark: [{ required: true, trigger: "blur", validator: remark }],
        equipment_id: [
          { required: true, message: "请选择广告机", trigger: "blur" }
        ]
      },
      createDisabled: true,
      updateDisabled: true,
      loading: false,
      industryOptions: [],
      areaOptions: [],
      areaCount: undefined,
      videoOptions: [],
      videoCount: undefined,
      industryCount: undefined,
      pageSize: 20,
      equipmentOptions: [],
      equipmentCount: undefined,
      permission: {
        add: false,
        del: false,
        update: false,
        review: false
      },
      pickerOptionsB: {
        // 限制时间
        // selectableRange: ['22:00:00 - 23:59:59','00:00:00 - 02:00:00'],
        // 限制日期
        disabledDate: this.disabledDateB
      },
      pickerOptionsE: {
        disabledDate: this.disabledDateE
      },
      pickerOptionsBT: {
        disabledDate: this.disabledDateBT
      },
      pickerOptionsET: {
        disabledDate: this.disabledDateET
      }
    };
  },
  computed: {
    operWidth: function() {
      let itemCount = 1;
      if (this.permission.del) {
        itemCount += 1;
      }
      if (this.permission.update) {
        itemCount += 1;
      }
      if (this.permission.review) {
        itemCount += 1;
      }
      return itemCount * 80 + "px";
    }
  },
  created() {
    if (this.$store.state.permission.jurisdiction === "*") {
      this.permission.add = true;
      this.permission.del = true;
      this.permission.update = true;
      this.permission.review = true;
      // this.permission.disable = true;
    } else {
      const jurisdiction = this.$store.state.permission.jurisdiction.split(",");
      jurisdiction.forEach(element => {
        const id = parseInt(element);
        if (id === 192) {
          this.permission.add = true;
        } else if (id === 194) {
          this.permission.del = true;
        } else if (id === 195) {
          this.permission.update = true;
        } else if (id === 193) {
          this.permission.review = true;
        }
      });
    }
    this.type = JSON.parse(getToken()).type;
    this.getList();
  },
  methods: {
    disabledDateB(time) {
      if (this.listQuery.endTime) {
        return (
          time.getTime() >
          new Date(this.listQuery.endTime).getTime() + 24 * 3600 * 1000 - 8.64e7
        );
      }
    },
    disabledDateE(time) {
      if (this.listQuery.startTime) {
        return (
          time.getTime() < new Date(this.listQuery.startTime).getTime() - 8.64e6
        );
      }
    },
    disabledDateBT(time) {
      let returnData = time.getTime() < Date.now() - 8.64e7;
      if (this.temp.end_time) {
        returnData =
          time.getTime() >
            new Date(this.temp.end_time).getTime() +
              24 * 3600 * 1000 -
              8.64e7 || time.getTime() < Date.now() - 8.64e7;
      }
      return returnData;
    },
    disabledDateET(time) {
      let returnData = time.getTime() < Date.now() - 8.64e7;
      if (this.temp.start_time) {
        returnData =
          time.getTime() < new Date(this.temp.start_time).getTime() - 8.64e6 ||
          time.getTime() < Date.now() - 8.64e7;
      }
      return returnData;
    },
    getVideoList(pageNumber = 1, search = "") {
      this.getvideoName(pageNumber, search);
    },
    getVideoid(data) {
      if (data.length > 0) {
        this.temp.video_id = data[0].id;
        this.temp.video_name = data[0].name;
      } else {
        this.temp.video_id = undefined;
        this.temp.video_name = "";
      }
    },
    getAreaList(pageNumber = 1, search = "") {
      this.getArea(pageNumber, search);
    },
    getAreaid(data) {
      if (data.length > 0) {
        this.temp.regions_id = data[0].id;
        this.temp.regions_name = data[0].name;
      } else {
        this.temp.regions_id = undefined;
        this.temp.regions_name = "";
      }
    },
    getIndustryList(pageNumber = 1, search = "") {
      this.getIndustry(pageNumber, search);
    },
    getEquipmentList(pageNumber = 1, search = "") {
      this.getEquipment(pageNumber, search);
    },
    getEquipmentid(data) {
      if (data.length > 0) {
        this.temp.equipment_id = data[0].id;
        this.temp.equipment_code = data[0].name;
      } else {
        this.temp.equipment_id = undefined;
        this.temp.equipment_code = "";
      }
    },
    getIndustryid(data) {
      if (data.length > 0) {
        this.temp.trade_id = data[0].id;
        this.temp.trade_name = data[0].name;
      } else {
        this.temp.trade_id = undefined;
        this.temp.trade_name = "";
      }
    },
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page
      };
      if (this.listQuery.name) {
        data["name"] = this.listQuery.name;
      }
      if (this.listQuery.status) {
        data["status"] = this.listQuery.status;
      }
      if (this.listQuery.play_status) {
        data["play_status"] = this.listQuery.play_status;
      }
      if (this.listQuery.regions_name) {
        data["regions_name"] = this.listQuery.regions_name;
      }
      if (this.listQuery.trade_name) {
        data["trade_name"] = this.listQuery.trade_name;
      }
      if (this.listQuery.startTime) {
        data["startTime"] = this.listQuery.startTime;
      }
      if (this.listQuery.endTime) {
        const date = new Date(this.listQuery.endTime);
        data["endTime"] = this.timestampToTime(
          date.getTime() + (60 * 60 * 24 * 1000 - 1)
        );
      }
      const adPlayRuleListPath = {
        // 获取广播列表
        company: "STQ",
        api: "pc_Broadcast_index",
        version: "1.0",
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(adPlayRuleListPath), res => {
        if (res) {
          this.socketData(res);
          this.listLoading = false;
        } else {
          this.$message.error(" 获取广播列表失败 ");
          this.listLoading = false;
        }
      });
    },
    timeFormat(time) {
      const date = new Date(time);
      const Y = date.getFullYear();
      const M =
        date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1;
      const D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return Y + "." + M + "." + D;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleModifyStatus(row) {
      this.$confirm("此操作将永久删除该规则, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const deleteRulePath = {
            company: "STQ",
            api: "pc_Broadcast_delete",
            version: "1.0",
            data: {
              id: row.id
            }
          };
          this.socketApi.sendSock(JSON.stringify(deleteRulePath), res => {
            if (res) {
              this.socketData(res);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        content: "",
        trade_id: "",
        trade_name: "",
        regions_id: "",
        regions_name: "",
        equipment_id: "",
        equipment_code: "",
        count: "",
        play_time: "",
        start_time: "",
        end_time: ""
      };
      this.temptime = [{ start: "", end: "" }];
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        name: "",
        status: "",
        play_status: "",
        regions_name: "",
        trade_name: "",
        startTime: "",
        endTime: ""
      };
      this.getList();
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    checkRule() {
      // 检测添加规则
      if (
        !(this.temp.regions_id || this.temp.trade_id || this.temp.equipment_id)
      ) {
        this.$message.error(" 区域、行业、广告机号必须选择一种 ");
        return false;
      } else if (
        (this.temp.regions_id && this.temp.equipment_id) ||
        (this.temp.trade_id && this.temp.equipment_id)
      ) {
        this.$message.error(" 区域、行业不能与广告机号同时选择 ");
        return false;
      }
    },
    createData() {
      // 添加广播规则
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.checkRule() === false) {
            return false;
          }
          if (this.createDisabled) {
            this.createDisabled = false;
            const data = {
              name: this.temp.name
            };
            if (this.temp.regions_id) {
              data["regions_id"] = this.temp.regions_id;
              data["regions_name"] = this.temp.regions_name;
            }
            if (this.temp.trade_id) {
              data["trade_id"] = this.temp.trade_id;
              data["trade_name"] = this.temp.trade_name;
            }
            if (this.temp.equipment_id) {
              data["equipment_id"] = this.temp.equipment_id;
              data["equipment_code"] = this.temp.equipment_code;
            }
            if (this.temp.start_time) {
              data["start_time"] = this.temp.start_time;
            }
            if (this.temp.end_time) {
              data["end_time"] = this.temp.end_time;
            }
            if (this.temp.content) {
              data["content"] = this.temp.content;
            }
            if (this.temp.count) {
              data["count"] = this.temp.count;
            }
            const addRulePath = {
              company: "STQ",
              api: "pc_Broadcast_add",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(addRulePath), res => {
              if (res) {
                this.socketData(res);
              } else {
                this.$message.error(" 添加失败 ");
              }
              setTimeout(() => {
                this.createDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    handleReview(row) {
      // 打开审核弹窗
      this.temp = Object.assign({}, row); // copy obj
      this.temptime = JSON.parse(this.temp.play_time);
      // if (this.temp.regions_id) {
      //   this.temp.regions_id = parseInt(this.temp.regions_id);
      // }
      // if (this.temp.trade_id) {
      //   this.temp.trade_id = parseInt(this.temp.trade_id);
      // }
      this.dialogStatus = "review";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate(row) {
      // 打开编辑弹窗
      this.temp = Object.assign({}, row); // copy obj
      if (this.temp.region_id) {
        this.temp.region_id = parseInt(this.temp.region_id);
      }
      if (this.temp.trade_id) {
        this.temp.trade_id = parseInt(this.temp.trade_id);
      }
      this.temptime = JSON.parse(this.temp.play_time);
      this.temp.data = [this.temp.start_time, this.temp.end_time];
      if (this.temp.is_coupon === 1) {
        this.temp.is_coupon = true;
      } else {
        this.temp.is_coupon = false;
      }
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleRead(row) {
      // 打开查看弹窗
      this.temp = Object.assign({}, row); // copy obj
      if (this.temp.is_coupon === 1) {
        this.temp.is_coupon = true;
      } else {
        this.temp.is_coupon = false;
      }
      this.temptime = JSON.parse(this.temp.play_time);
      this.dialogStatus = "read";
      this.dialogFormRead = true;
    },
    handleDisable(row) {
      const checkRulePath = {
        company: "STQ",
        api: "pc_Broadcast_edit",
        version: "1.0",
        data: {
          id: row.id,
          status: 4
        }
      };
      this.socketApi.sendSock(JSON.stringify(checkRulePath), res => {
        if (res) {
          this.socketData(res);
        } else {
          this.$message.error(" 启用失败 ");
        }
      });
    },
    handleEnable(row) {
      const checkRulePath = {
        company: "STQ",
        api: "pc_Broadcast_edit",
        version: "1.0",
        data: {
          id: row.id,
          status: 2
        }
      };
      this.socketApi.sendSock(JSON.stringify(checkRulePath), res => {
        if (res) {
          this.socketData(res);
        } else {
          this.$message.error(" 禁用失败 ");
        }
      });
    },
    reviewData() {
      // 审核规则信息
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.checkRule() === false) {
            return false;
          }
          if (this.updateDisabled) {
            this.updateDisabled = false;
            const data = {
              id: this.temp.id,
              status: this.temp.status
            };
            if (this.temp.check_remark) {
              data["check_remark"] = this.temp.check_remark;
            }
            const checkRulePath = {
              company: "STQ",
              api: "pc_Broadcast_check",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(checkRulePath), res => {
              if (res) {
                this.socketData(res);
              } else {
                this.$message.error(" 审核失败 ");
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    updateData() {
      // 更新广播信息
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.checkRule() === false) {
            return false;
          }

          const data = {
            id: this.temp.id,
            name: this.temp.name,
            regions_id: this.temp.regions_id,
            regions_name: this.temp.regions_name,
            trade_id: this.temp.trade_id,
            trade_name: this.temp.trade_name,
            equipment_id: this.temp.equipment_id,
            equipment_code: this.temp.equipment_code,
            start_time: this.temp.start_time,
            end_time: this.temp.end_time,
            play_time: this.temptime,
            content: this.temp.content,
            count: this.temp.count
          };
          const editRulePath = {
            company: "STQ",
            api: "pc_Broadcast_edit",
            version: "1.0",
            data: data
          };
          this.socketApi.sendSock(JSON.stringify(editRulePath), res => {
            if (res) {
              this.socketData(res);
            } else {
              this.$message.error(" 更新失败 ");
            }
            setTimeout(() => {
              this.updateDisabled = true;
            }, 1000);
          });
        }
      });
    },
    // 区域行业选择
    getIndustry(pageNumber, search) {
      const industryIndexPath = {
        company: "STQ",
        api: "pc_trade_index",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize,
          type: 2
        }
      };
      this.socketApi.sendSock(JSON.stringify(industryIndexPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    getArea(pageNumber, search) {
      const areaIndexPath = {
        company: "STQ",
        api: "pc_region_index",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize
        }
      };
      this.socketApi.sendSock(JSON.stringify(areaIndexPath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 视频源名查询
    getvideoName(pageNumber, search) {
      const adVideoGetNamePath = {
        company: "STQ",
        api: "pc_AdVideo_getName",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize
        }
      };
      this.socketApi.sendSock(JSON.stringify(adVideoGetNamePath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    getEquipment(pageNumber, search) {
      const getEquipmentCodePath = {
        company: "STQ",
        api: "pc_equipment_getEquipmentCode",
        version: "1.0",
        data: {
          name: search,
          page: pageNumber,
          rows: this.pageSize
        }
      };
      this.socketApi.sendSock(JSON.stringify(getEquipmentCodePath), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "pc_Broadcast_index") {
            // 广播列表
            this.total = resj.count;
            this.list = resj.data;
          } else if (resj.api === "pc_Broadcast_check") {
            // 广播审核
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "审核成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_Broadcast_edit") {
            // 广播编辑
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_Broadcast_add") {
            // 广播添加
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
          } else if (resj.api === "pc_Broadcast_delete") {
            // 广播删除
            this.getList();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          } else if (resj.api === "pc_region_index") {
            // 地区模糊查询
            const options = [];
            resj.data.forEach(element => {
              options.push({ id: element.id, name: element.region_name });
            });
            this.areaOptions = options;
            this.areaCount = resj.count;
          } else if (resj.api === "pc_trade_index") {
            // 行业模糊查询
            this.industryOptions = resj.data;
            this.industryCount = resj.count;
          } else if (resj.api === "pc_AdVideo_getName") {
            // 视频源模糊搜索
            this.videoOptions = resj.data;
            this.videoCount = resj.count;
          } else if (resj.api === "pc_equipment_getEquipmentCode") {
            // 设备编号模糊查询
            const options = [];
            resj.data.forEach(element => {
              options.push({ id: element.id, name: element.code });
            });
            this.equipmentOptions = options;
            this.equipmentCount = resj.count;
          }
        }
      }
    },
    // 时间转换
    getData(data) {
      var date = new Date(data);
      var Y = date.getFullYear();
      var M = date.getMonth() + 1;
      var D = date.getDate();
      return Y + "-" + M + "-" + D;
    },
    isCoupon(data) {
      data = parseInt(data);
      if (data === 1) {
        return "是";
      } else {
        return "否";
      }
    }
  }
};
</script>
